package com.ewhale.feitengguest.ui.shop.task

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.EditTaskDto
import com.ewhale.feitengguest.dto.ShopTaskDto
import com.ewhale.feitengguest.dto.TabEntity
import com.ewhale.feitengguest.presenter.shop.task.STaskPresenter
import com.ewhale.feitengguest.ui.shop.release.ReleaseTaskActivity
import com.ewhale.feitengguest.ui.shop.task.adapter.STaskAdapter
import com.ewhale.feitengguest.view.shop.task.STaskView
import com.ewhale.feitengguest.widget.IncreaseNumberDialog
import com.ewhale.feitengguest.widget.IncreasePriceDialog
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.simga.library.activity.MBaseFragment
import com.simga.library.utils.Dp2PxUtil
import com.simga.library.widget.HintDialog
import com.simga.library.widget.RecycleViewDivider
import kotlinx.android.synthetic.main.fragment_shop_task.*
import java.math.BigDecimal
import java.util.*

class STaskFragment : MBaseFragment<STaskPresenter>(), STaskView {
    override fun getViewId(): Int {
        return R.layout.fragment_shop_task
    }

    private val mTitles = arrayOf("进行中", "暂停中", "待审核", "不通过", "已结束")
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private val mAdapter by lazy(LazyThreadSafetyMode.NONE) { STaskAdapter() }
    private var pageNumber = 1
    private var status = 2
    private var priceDialog: IncreasePriceDialog? = null
    private var numberDialog: IncreaseNumberDialog? = null
    private val myReceiver by lazy(LazyThreadSafetyMode.NONE) { MyReciver() }

    override fun init(savedInstanceState: Bundle?) {
        val filter = IntentFilter()
        filter.addAction("UPDATE_TASK_LIST")
        activity!!.registerReceiver(myReceiver, filter)
        for (i in mTitles.indices) {
            mTabEntities.add(TabEntity(mTitles[i], 0, 0))
        }
        acty_main_tab.setTabData(mTabEntities)
        listview.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
            addItemDecoration(RecycleViewDivider(mContext,
                    Dp2PxUtil.dip2px(mContext, 10f)))
        }
        xloading_view.showLoading()
        presenter.loadTaskList(pageNumber, status)
    }

    override fun showTaskList(list: List<ShopTaskDto>) {
        if (pageNumber == 1) {
            mAdapter.setNewData(list)
        } else {
            mAdapter.addData(list)
        }
        if (mAdapter.mData.size == 0) {
            xloading_view.showEmpty()
        } else {
            xloading_view.showContent()
        }
        onLoad(list.size)
    }

    private fun onLoad(size: Int) {
        if (ref_layout == null) {
            return
        }
        ref_layout.finishRefreshLoadingMore()
        if (size < 10) {
            ref_layout.enableLoadMore(false)
        } else {
            ref_layout.enableLoadMore(true)
        }
    }

    override fun initListener() {
        super.initListener()
        acty_main_tab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                when (position) {
                    0 -> status = 2
                    1 -> status = 5
                    2 -> status = 1
                    3 -> status = 4
                    4 -> status = 3
                }
                mAdapter.currentTab = position
                mAdapter.notifyDataSetChanged()
                pageNumber = 1
                xloading_view.showLoading()
                presenter.loadTaskList(pageNumber, status)
            }

            override fun onTabReselect(position: Int) {}
        })
        ref_layout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                super.onLoadMore(refreshLayout)
                pageNumber++
                presenter.loadTaskList(pageNumber, status)
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                super.onRefresh(refreshLayout)
                pageNumber = 1
                presenter.loadTaskList(pageNumber, status)
            }
        })
        xloading_view.setOnRetryClickListener {
            pageNumber = 1
            xloading_view.showLoading()
            presenter.loadTaskList(pageNumber, status)
        }
        mAdapter.setOnItemClickListener { _, item, _ ->
            STaskDetailActivity.open(mContext, item.id, STaskDetailActivity.NORAL_OPEN)
        }
        mAdapter.suspend = {
            val hintDialog = HintDialog(mContext, "提示", "您确定暂停此任务吗？", arrayOf("取消", "确定"))
            hintDialog.setCallback(object : HintDialog.Callback {
                override fun callback() {
                    presenter!!.suspendTask(mAdapter.mData[it].id, it)
                }

                override fun cancle() {}
            })
            hintDialog.show()
        }
        mAdapter.edit = {
            presenter.loadTaskEditDetail(mAdapter.mData[it].id)
        }
        mAdapter.start = {
            val hintDialog = HintDialog(mContext, "提示", "您确定开启此任务吗？", arrayOf("取消", "确定"))
            hintDialog.setCallback(object : HintDialog.Callback {
                override fun callback() {
                    presenter!!.startTask(mAdapter.mData[it].id, it)
                }

                override fun cancle() {}
            })
            hintDialog.show()
        }
        mAdapter.increasePrice = { position: Int, item: ShopTaskDto ->
            if (priceDialog == null) {
                priceDialog = IncreasePriceDialog(mContext)
            }
            priceDialog!!.setData(item.img, item.title, item.beforeUnitPrice)
            priceDialog!!.setListenter(object : IncreasePriceDialog.onClickListenter {
                override fun onClickCommit(price: String) {
                    IncreasePayActivity.open(mContext, item.id, (BigDecimal(price).subtract(item.beforeUnitPrice)).multiply(BigDecimal(item.totalNum - item.finishNum)).stripTrailingZeros().toPlainString(), BigDecimal(price).subtract(item.beforeUnitPrice).stripTrailingZeros().toPlainString(), IncreasePayActivity.INCREASE_PRICE)
                    priceDialog = null
                }
            })
            priceDialog!!.show()
        }
        mAdapter.IncreaseQuota = { position: Int, item: ShopTaskDto ->
            if (numberDialog == null) {
                numberDialog = IncreaseNumberDialog(mContext)
            }
            numberDialog!!.setData(item.img, item.title, item.totalNum - item.finishNum)
            numberDialog!!.setListenter(object : IncreaseNumberDialog.onClickListenter {
                override fun onClickCommit(number: String) {
                    IncreasePayActivity.open(mContext, item.id, item.beforeUnitPrice.multiply(BigDecimal(number)).stripTrailingZeros().toPlainString(), number.toInt(), IncreasePayActivity.INCREASE_NUMBER)
                    numberDialog = null
                }
            })
            numberDialog!!.show()
        }
        mAdapter.delete = {
            var hint = ""
            if (acty_main_tab.currentTab == 3) {
                hint = "确定删除该任务？"
            } else if (acty_main_tab.currentTab == 4) {
                hint = "删除任务后，用户提示的信息将被清除，确定删除该任务？"
            }
            val hintDialog = HintDialog(mContext, "提示", hint, arrayOf("取消", "确定"))
            hintDialog.setCallback(object : HintDialog.Callback {
                override fun callback() {
                    presenter!!.deleteTask(mAdapter.mData[it].id, it)
                }

                override fun cancle() {}
            })
            hintDialog.show()
        }
        mAdapter.taskEnd = {
            val hintDialog = HintDialog(mContext, "提示", "您确定提前结束此任务吗？", arrayOf("取消", "确定"))
            hintDialog.setCallback(object : HintDialog.Callback {
                override fun callback() {
                    presenter!!.endTask(mAdapter.mData[it].id, it)
                }

                override fun cancle() {}
            })
            hintDialog.show()
        }
    }

    override fun deleteSuccess(position: Int) {
        showToast("删除成功")
        mAdapter.removeAt(position)
        if (mAdapter.mData.size == 0) {
            xloading_view.showEmpty()
        }
    }

    override fun suspendSuccess(position: Int) {
        showToast("任务已暂停")
        mAdapter.removeAt(position)
        if (mAdapter.mData.size == 0) {
            xloading_view.showEmpty()
        }
    }

    override fun startSuccess(position: Int) {
        showToast("任务已开启")
        mAdapter.removeAt(position)
        if (mAdapter.mData.size == 0) {
            xloading_view.showEmpty()
        }
    }

    override fun endSuccess(position: Int) {
        showToast("任务已结束")
        mAdapter.removeAt(position)
        if (mAdapter.mData.size == 0) {
            xloading_view.showEmpty()
        }
    }

    override fun showEditDetail(editTaskDto: EditTaskDto) {
        ReleaseTaskActivity.open(mContext, editTaskDto)
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String, message: String) {
        showErrorMsg(code, message)
        onLoad(-1)
        if (postCode == 1 || postCode == -10086) {
            xloading_view.showError()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        activity!!.unregisterReceiver(myReceiver)
    }

    inner class MyReciver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent!!.action == "UPDATE_TASK_LIST") {
                pageNumber = 1
                presenter.loadTaskList(pageNumber, status)
            }
        }
    }
}
